package cfg

import (
	"bili-server/app/log"
	"encoding/json"
	"fmt"
	"os"
	"sync"
)

type Config struct {
	WebURL string   `json:"web_url"`
	Dir    []string `json:"dir"`
}

const filename = "config.json"

var lock = sync.RWMutex{}

func GetConfig() *Config {
	return read()
}

func write(c *Config) error {
	content, _ := json.MarshalIndent(c, "", "  ")
	return os.WriteFile(filename, content, 0666)
}

// 读取配置文件
func read() *Config {
	lock.RLock()
	defer lock.RLock()
	content, err := os.ReadFile(filename)
	if err != nil {
		if os.IsNotExist(err) {
			log.L.Error("文件不存在: ", err)
		}
	}
	var c Config
	err = json.Unmarshal(content, &c)
	if err != nil {
		log.L.Error(err)
	}
	return &c
}

// 初始化配置文件
func init() {
	lock.Lock()
	defer lock.Unlock()
	content, err := os.ReadFile(filename)
	if len(content) == 0 || os.IsNotExist(err) {
		content, err := json.MarshalIndent(Config{
			WebURL: "localhost:8008",
		}, "", "  ")
		if err != nil {
			log.L.Error(err)
		}
		file, err := os.Create(filename)
		if err != nil {
			log.L.Error("创建文件失败:", err)
		}
		n, err := file.Write(content)
		if err != nil {
			log.L.Error("写入失败:", err)
		}
		fmt.Println("n:", n)
	}
}
